<template>
    <div class="user">
        <el-row>
            <el-col :span="24">
                <el-breadcrumb separator-class="el-icon-arrow-right">
                    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item>用户管理</el-breadcrumb-item>
                    <el-breadcrumb-item>用户列表</el-breadcrumb-item>
                </el-breadcrumb>
            </el-col>
        </el-row>

        <el-row>
            <el-col :span="24">
                <el-input class="search-input" v-model="query" @keydown.native.enter="initUserList()" placeholder="请输入内容">
                    <el-button slot="append" @click="initUserList()" icon="el-icon-search"></el-button>
                </el-input>
                <el-button type="info" plain @click="addUser()">添加用户</el-button>
            </el-col>
            <div style="clear:both;"></div>
            
            <div class="table_container">
                <el-table
                :data="userlist"
                :border="border"
                style="width: 100%"  v-loading="loading">
                <el-table-column
                    type="index"
                    width="50">
                </el-table-column>
                <el-table-column
                  prop="username"
                  label="姓名"
                  width="180">
                </el-table-column>
                <el-table-column
                  prop="email"
                  label="邮箱"
                  width="180">
                </el-table-column>
                <el-table-column
                  prop="mobile"
                  label="电话">
                </el-table-column>

                <el-table-column label="用户状态">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" @change="changeuserState(scope.row)"></el-switch>
                    </template>
                </el-table-column>

                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button
                        size="mini"
                        type="primary"
                        icon="el-icon-edit"
                        plain @click="editUser(scope.row)"></el-button>

                        <el-button
                        size="mini"
                        type="success"
                        icon="el-icon-check"
                        plain @click="grantUser(scope.row)"></el-button>

                        <el-button
                        size="mini"
                        type="danger"
                        icon="el-icon-delete" @click="deleteUser(scope.row)"></el-button>
                    </template>
                </el-table-column>
                
                </el-table>
            </div>
            

            <div class="page">
                 <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="1"
                    :page-sizes="[10, 20, 30, 40]"
                    :page-size="10"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
            </div>
        </el-row>

        <!-- 添加用户弹出框 -->
        <el-dialog title="添加用户" :visible.sync="addDialogFormVisible">
            <el-form :model="addForm" label-width="80px" :rules="rules" ref="addUserForm">

                <el-form-item label="用户名称" prop="username">
                    <el-input v-model="addForm.username" maxlength="12" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password" maxlength='12' autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="addForm.mobile" autocomplete="off"></el-input>
                </el-form-item>
            
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="addDialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUserSubmit('addUserForm')">确 定</el-button>
            </div>
        </el-dialog>

          <!-- 编辑用户弹出框 -->
        <el-dialog title="编辑用户" :visible.sync="editDialogFormVisible">
            <el-form :model="editForm" label-width="80px" :rules="rules" ref="editUserForm">

                <el-form-item label="用户名称" prop="username">
                    <el-input v-model="editForm.username" maxlength='12' :disabled="true" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="editForm.mobile" autocomplete="off"></el-input>
                </el-form-item>
            
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="editDialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUserSubmit('editUserForm')">确 定</el-button>
            </div>
        </el-dialog>

            <!-- 分配角色弹出框 -->
        <el-dialog title="分配角色" :visible.sync="grantDialogFormVisible">
            <el-form :model="grantForm" label-width="120px" :rules="rules" ref="grantUserForm">

                <el-form-item label="用户名称" prop="username">
                    <el-tag type="info">{{grantForm.username}}</el-tag>
                </el-form-item>
                <el-form-item label="请选择角色">
                    <el-select v-model="roleId" placeholder="请选择角色">
                        <el-option v-for="item in rolelist" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="grantDialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="grantUserSubmit('grantUserForm')">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import {getUserList,changeUserState,addNewUser,editUserMessage,editUser,deleteUserMessage,getRoleList,grantUserRole} from '@/api/api.js'
export default {
    data() {
      return {
        loading:'',
        border:true,
        userlist:[],
        query:'',
        total:0,
        pagesize:10,
        pagenum:1,
        addDialogFormVisible:false,
        editDialogFormVisible:false,
        grantDialogFormVisible:false,
        addForm:{
            username:'',
            password:'',
            email:'',
            mobile:''
        },
        editForm:{
            username:'',
            email:'',
            mobile:'',
            id:''
        },
        grantForm:{},
        rolelist:[],
        roleId:'',//角色Id
        rules:{//添加用户表单校验规则
        username:[
            {required:true,message:'请输入用户名',trigger:'blur'}
            ],
        password:[
            {required:true,message:'请输入密码',trigger:'blur'}
            ],
        email:[
            {required:true,message:'请输入邮箱地址',trigger:'blur'},
            {type:'email',message:'请输入正确的邮箱地址',trigger:'blur,change'}
            ],
        mobile:[
            {required:true,message:'电话不能为空'},
            {pattern:/^1[34578]\d{9}$/,message:'目前只支持中国大陆的手机号码'}
            ]
        }
      }
    },
    methods: {
        handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.pagesize=val
        this.initUserList()
        },
        handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.pagenum=val
        this.initUserList()
        },
        initUserList() {
            this.loading=true;//初始化表之前显示loading效果
            getUserList({params:{query:this.query, pagenum: this.pagenum, pagesize: this.pagesize}}).then(res=>{
                if(res.meta.status===200){
                    this.userlist=res.data.users
                    this.total=res.data.total
                    this.loading=false;//初始化表之后关闭loading效果
                }
            })
        },
        changeuserState(row){
            changeUserState({uid:row.id,type:row.mg_state}).then(res=>{
                // console.log(res)
                if(res.meta.status===200){
                    this.$message({
                        type:'success',
                        message:'修改用户状态成功~'
                    })
                }else {
                    this.$message({
                        type:'warning',
                        message:res.meta.msg
                    })
                }
            })
        },
        addUser(){
            this.addDialogFormVisible=!this.addDialogFormVisible
        },
        addUserSubmit(formName){
            this.$refs[formName].validate(valide=>{
                if(valide){
                    addNewUser(this.addForm).then(res=>{
                        // console.log(res)
                        if(res.meta.status===201) {
                            this.$message({
                                type:'success',
                                message:'创建用户成功'
                            })
                        }else if(res.meta.status===400){
                            this.$message({
                                type:'warning',
                                message:res.meta.msg
                            })
                        }else{
                            this.$message({
                                type:'error',
                                message:"创建用户失败!"
                            })
                        }
                    })
                    this.addDialogFormVisible=false
                    this.initUserList()
                }
            })
        },
        editUser(row){
            this.editDialogFormVisible=!this.editDialogFormVisible
            editUserMessage(row).then(res=>{
                console.log(res);
                if(res.meta.status===200) {
                    this.editForm.username=res.data.username;
                    this.editForm.email=res.data.email;
                    this.editForm.mobile=res.data.mobile;
                    this.editForm.id=res.data.id;
                }
            })

        },
        editUserSubmit(formName){
             this.$refs[formName].validate(valide=>{
                 if(valide){
                     editUser(this.editForm).then(res=>{
                         if(res.meta.status===200){
                             this.$message({
                                 type:'success',
                                 message:'编辑用户成功'
                             })
                            
                         }else{
                             this.$message({
                                 type:'warning',
                                 message:'编辑用户失败'
                             })
                         }
                     })
                    this.editDialogFormVisible=false
                    this.initUserList()
                 }

             })
        },
        deleteUser(row){
            this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            deleteUserMessage(row.id).then(res=>{
                console.log(res)
                if(res.meta.status===200){
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.initUserList();
                }
            })
        }).catch(() => {
          this.$message({
                type: 'info',
                message: '已取消删除'
                });          
            });
        },
        grantUser(row) {
            this.grantForm=row;
            this.grantDialogFormVisible=!this.grantDialogFormVisible
            getRoleList().then(res=>{
                if(res.meta.status===200){
                    this.rolelist=res.data
                }
            })
        },
        grantUserSubmit(){
            if(!this.roleId){
                this.$message({
                    type:'error',
                    message:'请选择用户角色'
                })
            }else{
                 grantUserRole({id:this.grantForm.id,rid:this.roleId}).then(res=>{
                // console.log(res);
                if(res.meta.status===200) {
                    this.$message({
                        type:'success',
                        message:'设置角色成功'
                    })
                    this.grantDialogFormVisible=false;
                }else{
                    this.$message({
                        type:'error',
                        message:'设置角色失败'
                        })
                    }
                })
            }
           
        }
       
        
    },
    created() {
        this.initUserList()
    }
}
</script>

<style lang="scss" scoped>
    .user{
        .search-input {
            width:400px;
        }
        .table_container {
            padding: 15px 15px 15px 0;
            box-sizing:border-box;
            border:1px solid #EBEEF5;
        }
        .page{
            padding:5px 0;
            background-color:#D3DCE6;
        }
    }
</style>